package com.zixue.heima.helloNetty.EventLoopGroopDemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @ClassName : HelloClient
 * @Description : TODO
 * @Author : chunxiong
 * @Date : 2025/5/2 00:25
 * @Version 1.0
 */
@Slf4j
public class HelloClientFutureChannel {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
//connet方法是异步非阻塞,调用不关心结果,交给另外1个线程
        //2。1是 使用sycn方法同步处理结果
/*        channelFuture.sync();//阻塞房前线程 直到nio线程建立完毕  //这里看似没报错 能不能发送呢？ 不调用sync
        Channel channel = channelFuture.channel();
        log.info(",,,,,{}",channel);
        System.out.println("短点");*/

        //2。2 addLister（回调对象） 异步处理
         //异步：等结果的也不是我的主线程， 全交给另外线程， 执行玩了 回调
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            // nio线程建立完成后， 会调用这个
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                //和上面是同一个channel对象
                Channel channel = channelFuture.channel();
                log.info(",,,,,2 {}",channel);
            }
        });
    }
}
